package com.xiaouyudeguang.common.message.config;

import com.xiaouyudeguang.common.message.event.ChangedEvent;
import com.xiaouyudeguang.common.message.pusher.IEventPusher;
import com.xiaouyudeguang.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class EventPusherConfig {

    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired(required = false)
    private ApplicationContext context;

    @Bean
    @ConditionalOnMissingBean(IEventPusher.class)
    public IEventPusher defaultEventPusher() {
        return (type, tableName, condition, source) -> {
            if (condition) {
                ChangedEvent event = new ChangedEvent(source.getJson());
                event.setTableName(StringUtils.lowerCamel(tableName));
                event.setAppId(source.getAppId());
                event.setTenantId(source.getTenantId());
                event.setId(source.getId());
                event.setType(type.name());
                context.publishEvent(event);
                if (redisTemplate != null) {
                    redisTemplate.convertAndSend(event.getTableName(), event);
                }
            }
            return condition;
        };
    }
}